package com.szrca.ima.utils;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 系统加密解密请统一用此工具类.
 * @author yanglb
 * @version 1.0.0
 * @createDate: 2016-07-11
 * @modifyTime:
 */
public class PlatUtils implements ApplicationContextAware {

	/**
	 * 系统使用 AES 算法 对 字符串进行加密.
	 */
	public static final String ALGORITHM = "AES";
	
	/**
	 * 系统使用AES算法加密的密钥.
	 */
	public static final String PRIVATEKEY = "UPATHS_KEY";

	private static final Logger logger = Logger.getLogger(PlatUtils.class);

	private static ApplicationContext ctx;

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		ctx = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return ctx;
	}

	/**
	 * 返回系统默认的私钥
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static SecretKey generateSecretKey() throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
		keyGenerator.init(new SecureRandom(PRIVATEKEY.getBytes()));
		SecretKey key = keyGenerator.generateKey();
		return key;
	}

	/**
	 * 对传入的字符串使用系统默认的算法进行加密
	 * 
	 * @param source
	 * @return
	 * @throws PlatformException
	 */
	public static String encrypt(String source) throws Exception {
		if (source == null) {
			throw new NullPointerException("加密字符不允许为空");
		}
		String result = null;
		byte[] datas = source.getBytes();
		try {
			// Cipher对象实际完成加密操作
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, generateSecretKey());
			datas = cipher.doFinal(datas);
			result = (new String(Base64.encodeBase64(datas))).replace("\r", "")
					.replace("\n", "");
		} catch (Exception e) {
			logger.error(e);
			throw new Exception("系统加密出错", e);
		}
		return result;
	}

	/**
	 * 对传入的字符串使用系统的解密方法来解密，解密字符串必须是以前加过密的字符
	 * 
	 * @param source
	 * @return
	 * @throws PlatformException
	 */
	public static String decrypt(String source) throws Exception {
		if (source == null) {
			throw new NullPointerException("加密字符不允许为空");
		}
		String result = null;
		try {
			byte[] datas = Base64.decodeBase64(source.getBytes());
			// Cipher对象实际完成加密操作
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, generateSecretKey());
			datas = cipher.doFinal(datas);
			result = new String(datas);
		} catch (Exception e) {
			logger.error(e);
			throw new Exception("系统解密出错", e);
		}
		return result;
	}
}
